/*
 * @Descripttion: 全局路由钩子
 * @Author: 银河以北
 * @Date: 2021-09-19 22:30:45
 * @LastEditors: 银河以北
 * @LastEditTime: 2021-09-22 11:43:10
 */


//引入路由
import router from './index'

//引入VUEX
import store from '@/store'

//引入提示组件
import { ElNotification } from 'element-plus'

//引入获取从cookie获取token的方法
import { getToken } from '@/utils/auth' // get token from cookie

// 白名单重定向
const whiteList = ['/']

//前置钩子
router.beforeEach(async (to, from) => {
    const TOKEN = getToken()
    if (TOKEN) {
        const userInfo = store.getters.userInfo
        if (userInfo) {
            return
        } else {
            // await store.dispatch('GetInfo')
            // return
            store.dispatch('GetInfo').then(res => {
                return
            })
        }
    } else {
        if (whiteList.includes(to.path)) {
            return
        } else {
            ElNotification({
                title: 'token失效',
                message: '请重新登录',
                type: 'error'
            })
            return '/'
        }
    }
})


//后置钩子
router.afterEach((to, from, next) => {
    //遍历meta改变title
    if (to.meta.title) {

        //断言告诉ts 我知道to.meta.title是个string 不用检查了
        document.title = (to.meta.title || '银河以北') as string;
    }
    window.scrollTo(0, 0);
});

